/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package creature;

import java.awt.Color;
import java.util.Vector;
import world.World;

/**
 *
 * @author leadiv
 *  By Default a creature is a small green 1 pixel dot that runs east to west.
 */
public class Plant extends Creature {
    private float birthThreshold;
    private float deathcnt;
    private float deathThreshold;
    private float deathDelta;

    public Plant(int x, int y, int id) {
        super(x,y,id);

        this.birthThreshold = .26f;
        this.deathThreshold = (float)(Math.random() * .56);
        this.deathcnt = 1f;
        this.deathDelta = -(float)(Math.random() * .99);       // This controls how much availble food there is.
        this.setSkinColor(Color.RED);
    }
    
    @Override
    public void move(World w) {
       Color[] neighbors = new Color[8];
       int cnt=0, avg2, i;
       Vector<Integer> emptySpots = new Vector<Integer>();

       this.setSkinColor(Color.GREEN);
       
       neighbors[0] = w.getpix(this.getX()-1, this.getY()+1);
       neighbors[1] = w.getpix(this.getX()  , this.getY()+1);
       neighbors[2] = w.getpix(this.getX()+1, this.getY()+1);
       neighbors[3] = w.getpix(this.getX()-1, this.getY());
       neighbors[4] = w.getpix(this.getX()+1, this.getY());
       neighbors[5] = w.getpix(this.getX()-1, this.getY()-1);
       neighbors[6] = w.getpix(this.getX()  , this.getY()-1);
       neighbors[7] = w.getpix(this.getX()+1, this.getY()-1);


       // Create density mapping
       for(i=0; i<8; i++) {
           avg2 = neighbors[i].equals(Color.BLACK) ? 0 : 1;
           if(0 == avg2) {  // this spot is empty
               emptySpots.add(i);
           } else {
               cnt++;
           }
       }


       // as time wears on you have a higher probablity of dying
       this.deathcnt += this.deathDelta;
       if(this.deathcnt < this.deathThreshold) {
           this.setSkinColor(Color.BLACK);
           w.death(this.getX(), this.getY(), this.getId(), this);
           return;
       }

       if(cnt == 8) {
           //Nothing we can do, its too crowded.
           return;
       }

        if(Math.random() < this.birthThreshold) {
            int index = (int)(Math.random() * emptySpots.size());
            w.birth(World.MOVE[index].x + this.getX(), World.MOVE[index].y + this.getY());
            this.setSkinColor(Color.YELLOW);
        }
    }
}
